<template>
  <div class="basecSetting">
    <el-form-item label="所属公司" prop="subId" :rules="rules.subId">
      <el-select v-model="form.subId" class="maxSelect" @change="getDepartmentView" filterable>
        <el-option v-for="item in companyList" :key="item.subid" :value="item.subid" :label="item.subName"></el-option>
      </el-select>
    </el-form-item>
    <el-form-item label="适用范围" prop="scope" :rules="rules.scope">
      <el-cascader ref="scope" class="maxSelect" v-model="form.scope" :options="scopeArr" :props="props" clearable popper-class="cascaderClass"> </el-cascader>
    </el-form-item>
    <el-form-item label="计税规则" prop="taxType" :rules="rules.taxType">
      <el-select v-model="form.taxType" class="maxSelect">
        <el-option v-for="item in ruleArr.filter(item => !item.isHide)" :key="item.id" :value="item.value" :label="item.label"></el-option>
      </el-select>
    </el-form-item>
    <el-form-item label="计薪周期"
      ><span>{{ payCycle }}</span></el-form-item
    >
    <el-form-item label="税款所属月" prop="taxMonthType" :rules="rules.taxMonthType">
      <el-radio-group v-model="form.taxMonthType">
        <div v-for="item in typeArr" :key="item.id">
          <el-radio :label="item.value">{{ item.label }}</el-radio>
          <span>{{ item.hint }}</span>
        </div>
      </el-radio-group>
    </el-form-item>
    <el-form-item label="备注">
      <el-input v-model="form.remarks"></el-input>
    </el-form-item>
  </div>
</template>
<script>
import { diffArr, getCompanyList, getDepartmentView, getEmployeeSalaryList } from "@/util/xc/utils";
import { mapState } from "vuex";
// import { mapState } from 'vuex';

export default {
  name: "basicSetting",
  model: {
    prop: "form",
    event: "change"
  },
  props: {
    form: Object
  },
  data() {
    return {
      typeArr: [
        { id: 1, value: 1, label: "与工资所属月保持一致", hint: "例：3月算薪时，算税时薪资、税款所属月都默认为3月" },
        { id: 2, value: 2, label: "比工资所属月晚一个月", hint: "例：3月算薪时，算税时薪资所属月为3月、则税款所属月默认为4月；当跨年时，12月算薪时，则税款所属期默认为第二年1月" }
      ],
      props: { multiple: true, children: "childrenList", label: "departmentName", value: "departmentid" },
      payCycle: "当月1号",
      rules: {
        subId: { required: true, message: "请选择所属公司" },
        scope: { required: true, message: "请选择适用范围" },
        taxType: { required: true, message: "请选择计税规则" },
        taxMonthType: { required: true, message: "请选择税款所属月" }
      },
      scopeArr: []
    };
  },
  computed: {
    ...mapState({
      companyList: state => state.reward.companyList,
      userList: state => state.reward.userList,
      userInfo: state => state.common.userInfo,
      ruleArr: state => state.reward.ruleArr
    })
  },
  methods: {
    // 获取组件数据
    ...{
      async getData() {
        const { subId, taxType, taxMonthType, remarks, id } = this.form;
        const o = this.companyList.find(item => item.subid == subId) || {};
        const { companyid: companyId, subName } = o;
        const { payCycle } = this;
        const { scope, departmentList } = this.getScope(subId, companyId, id);
        // const arr = this.$refs.scope.getCheckedNodes().map(item => item.value);
        // const userList = this.userList.filter((item) => item.subId == subId && arr.includes(item.departmentId) && item.userType == taxType);
        // console.log(userList, JSON.parse(JSON.stringify(this.userList)), arr, scope);
        // if (!userList.length) return Promise.reject("当前部门下没有人员,请重新选择");
        console.log(scope, departmentList, this.form);
        return { subName, subId, companyId, scope, taxType, taxMonthType, payCycle, departmentList, remarks };
        // return Promise.reject("测试拦截");
      },

      /** 获取选中的最高级 */
      getScope(subId, companyId, salaryTId = 0) {
        const arr = this.$refs.scope.getCheckedNodes();
        console.group("获取选中最高级", arr, this.form.scope);
        const children = new Set();
        arr.forEach(item => {
          item.children.forEach(c => {
            children.add(c.uid);
          });
        });
        const newArr = arr.filter(item => !children.has(item.uid));
        console.log(children, newArr, arr);
        console.groupEnd();
        return {
          scope: newArr.map(item => item.label).join(","),
          departmentList: arr.map(item => {
            return { subId, companyId, salaryTId, departmentId: item.value, departmentName: item.label };
          })
        };
      },

      /** 数据对比 */
      dataDiff(now = this.form.scope, old = this.oldScope) {
        return diffArr(now, old);
      }
    },
    // 获取信息
    ...{
      async initData() {
        await getCompanyList();
        await getEmployeeSalaryList();
      },
      async getDepartmentView(e) {
        try {
          const { data } = await getDepartmentView(e);
          console.log(data);
          this.scopeArr = data;
        } catch {
          this.scopeArr = [];
        } finally {
          this.form.scope = [];
        }
        console.log(this.scopeArr);
      }
    },

    /** 数据回填 */
    async dataBackFill(data) {
      console.groupCollapsed("基础设置数据回填", data);
      await this.initData();
      await this.getDepartmentView(data.subId);
      this.form.scope = this.getCascaderData(data.departmentList);
      this.oldScope = JSON.parse(JSON.stringify(this.form.scope));
      console.log(this.form.scope);
      console.groupEnd();
    },
    getCascaderData(depList = []) {
      console.groupCollapsed("获取级联数据", depList, this.scopeArr);
      const targetArr = depList.map(item => item.departmentId);

      // 遍历书全部的可选择值
      this.cascaderAll = [];
      targetArr.forEach(target => {
        this.cascader = [];
        this.initialize(this.scopeArr, target);
      });

      // 筛选目标值
      const newArr = targetArr.map(target => this.cascaderAll.filter(item => item.includes(target))).flat(1);
      console.log(newArr);
      console.groupEnd();
      return newArr;
    },

    /** 遍历出全部的值 */
    initialize(arr = this.scopeArr, target) {
      console.groupCollapsed("开始选中遍历数组", arr, target);
      for (let i = 0; i < arr.length; i++) {
        const item = arr[i];
        this.cascader.push(item.departmentid);
        if (item?.childrenList?.length) this.initialize(item.childrenList, target);
        else {
          console.log(this.cascader);
          this.cascaderAll.push(JSON.parse(JSON.stringify(this.cascader)));
        }
        // console.log(this.cascader, this.cascaderAll);
        this.cascader.pop();
      }
      console.groupEnd();
    }
  },
  activated() {
    this.initData();
  }
};
</script>
<style lang="less" scoped>
.basecSetting {
  display: flex;
  flex-direction: column;
  .el-radio-group {
    line-height: 30px;
    span {
      font-size: 12px;
    }
  }
}
</style>
